// pages/member/editmobile/editmobile.js
var app = getApp();
// var WxParse = require('../../../wxParse/wxParse.js');
import uitil from '../../../utils/util.js';
var location = require("../../../mybehaviors/location/location");
var int = (app.globalData.statusBarHeight * 2) + 20;
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: int,
    repeatStatus: false,//防止快速
    isset: '',
    invite: '',
    isrequired: '',
    showChangeID: false,
    changidInfo: {
      uid: null,
      change_uid: null,
    },
    editType: '',
    uploadUrl: 'upload.uploadPic',
    form: {
      country: '86',
      mobile: '',
      mobileErr: '',
      password: '',
      passwordErr: '',
      confirm_password: '',
      confirm_passwordErr: '',
      captcha: '',
      province_name: '', //省
      city_name: '', //市
      area_name: '', //区
      province: '', //省ID
      city: '', //市ID
      area: '', //区ID
      address: '', //详细地址
      gender: '',
      custom_value: '',
      realname:'', //姓名
    },
    showBack: false,
    //性别----
    showSex: false,
    sexItems: [
      {
        name: '男'
      },
      {
        name: '女'
      }
    ],
    is_password: '0',
    customDatas: [],
    form_address: false,
    form_birthday: false,
    form_sex: false,
    date_v1: uitil.formatTime(new Date()).substring(0, 10),
    diydata: [],
    diyform: {},
    types: {
      "88": 'diyusername',
      "99": 'diypassword',
      "0": 'diyinput',
      "1": 'diytextarea',
      "3": 'diycheckbox',
      "4": 'diyradio',
      "2": 'diyselect',
      "7": 'diydate',
      "9": 'diycity',
      "5": 'diyimage',
    },
    agreementStatus: false,
    protocol_content: "",
    protocol_title: "",
    agreement_name: "平台协议",
    PlatformAgreement: '',
    showPlatformAgreement: false,
    imgcode: "",
    agreementCB: true,
    show2: false,
    start1: false,
    codetext: '获取短信验证码',
    //地区
    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    isValidation: true,
    currentDate: new Date().getTime(),
    yzredirect: '',
    nowtime: '2019-09-01',
    country_code: 0,
    fromApp: 0,
    anchorApplyBol: false,
    // 绑定手机优化 新加 2020_09_04
    isShowAddress: false,

    orderLocationObj: { positioning_success: 0, register_province: "", register_city: "" },

    // 自定义字段是否必填
    formOpen: false,
    default_invite:"",
    datas :{
      form_id:''
    },
    visibleSet: false,
    visibleSure: false,
    is_code:false,
    // 余额
    balance:'余额',
    // 积分
    point:'积分'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let userLocationFlag = await this.checkAlbum('scope.userLocation');
    console.log("userLocationFlag", userLocationFlag);
    if (!userLocationFlag) {
      return this.tips("获取位置失败，请重新进入后授权");
    }

    if (!app.globalData.qqmapkey) {
      app._getTemplate().then(res => {
        this.getCurrentOrderLocation();
      });
    } else {
      this.getCurrentOrderLocation();
    }


    if (options.editType) {
      this.setData({
        editType: options.editType
      });
    }
    if(options.is_code){
      this.data.is_code = true;
    }
    if (options.anchorApply) {
      // this.data.anchorApplyBol = true
      this.setData({
        anchorApplyBol: true
      });
    }
    if (options.code) {
      this.setData({
        "form.invite_code": options.code
      });
    }
    if (options.logintype) {
      this.data.yzredirect = app.getyzredirect();
    }
    if (options.fromApp && options.fromApp != 0) {
      this.setData({
        fromApp: options.fromApp
      });
    }

    //加载地址数据初始化
    this._initAddressInfo();

    if (options.num) {
      this.setData({
        "form.mobile": options.num
      });
    }
    this.getAllData();
    //加载地址数据初始化
    this._initAddressInfo();
    // this._initInviteCode();
    // this._getDiyFormStatus();
    // this._getProtocolStatus();
    // this.getimgdata();
    let timestamp = new Date().getTime();
    let nowtime = this.timestampToTime(timestamp);
    let name = wx.getStorageSync('userInfo');
    this.setData({
      nowtime: nowtime,
      nickName: name.userInfo?name.userInfo.nickName:''
    });
  },
  fillInCode() {
    this.setData({
      'form.invite_code': this.data.default_invite
    });
  },
  getPhoneNumber(e) {
    let info = e.detail;
    if(info.errMsg == 'getPhoneNumber:ok') {
      this.getPhoneM(info.code);
    }
  },
  back() {
    wx.navigateBack({
      delta: 1,
    });
  },
  //详细地址值绑定
  addressinp(e) {
    let val = e.detail.value;
    this.setData({
      'form.address': val
    });
  },
  getPhoneM(info) {
    let urlStr = app.getNetAddresss('member.member.miniMemberMobile');
    let that = this;
    app._postNetWork({
      url: urlStr,
      data: {
        code: info,
        not_validate_page: '0'
      },
      showToastIn: false,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            'form.mobile': res.data.phone_info.purePhoneNumber
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) { }
    });
  },
  sexSelectBtn(e) {
    let val = e.detail.name;
    if (val == '男') {
      this.setData({
        'form.gender': '1',
        sexName: '男'
      });
    } else if (val == '女') {
      this.setData({
        'form.gender': '0',
        sexName: '女'
      });
    }
    this.setData({
      showSex: false
    });
  },
  sexClose() {
    this.setData({
      showSex: false
    });
  },
  bindDateChange_v1(e) {
    this.setData({
      'form.birthday': e.detail.value
    });
  },
  //生日选择
  openPicker_v1() {
    this.setData({
      birthdayShow: true
    });
  },
  //显示性别设置
  showSexInfo() {
    this.setData({
      showSex: true
    });
  },
  // 关闭选择收货地址
  _closeDateLw_v1: function () {
    this.setData({
      showAdd_v1: false
    });
  },
  //所在地选择显示
  showAddBtn_v1() {
    this.setData({
      showAdd_v1: true
    });
  },
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log('地址信息准备就绪');
        that._getProvinceData();
      },
      fail: function (res) {
        app._getNetWork({
          url: app.getNetAddresss('member.member-address.address'),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: 'provinceData',
              data: province
            });
            wx.setStorage({
              key: 'cityData',
              data: city
            });
            wx.setStorage({
              key: 'districtData',
              data: district
            });
            that._initAddressInfo();
          },
          fail: function (res) { },
          state: true
        });
      }
    });
  },
  //初始化城市
  _initDistrict(data, district) {
    if (!app._isTextEmpty(data)) {
      if (!app._isTextEmpty(data.myform.form)) {
        this.setData({
          isShowAddress: data.myform.base.address == 1 ? true : false
        });
      }
      this.setData({
        'form.province': data.province,
        'form.province_name': data.province_name,
        'form.city': data.city,
        'form.city_name': data.city_name,
        'form.area': data.area,
        'form.area_name': data.area_name,
        districtName:
          data.province_name + ' ' + data.city_name + ' ' + data.area_name,
        'form.address': data.address
      });
      return;
    }

    if (!app._isTextEmpty(district)) {
      this.setData({
        'form.province': district.itemValue1,
        'form.province_name': district.itemName1,
        'form.city': district.itemValue2,
        'form.city_name': district.itemName2,
        'form.area': district.itemValue3,
        'form.area_name': district.itemName3
      });
      this.setData({
        districtName:
          district.itemName1 +
          ' ' +
          district.itemName2 +
          ' ' +
          district.itemName3
      });
    }
  },
  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        that.setData({
          provinceData: res.data
        });
        that.setData({
          'selectAddressData[0].name':
            res.data[that.data.pickerValue[0]].areaname,
          'selectAddressData[0].id': res.data[that.data.pickerValue[0]].id,
          'selectAddressData[0].index': that.data.pickerValue[0]
        });
        that._getCityData();
      }
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    var that = this;
    var _keyName = 'cityData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        that.setData({
          cityData: _json
        });
        that.setData({
          'selectAddressData[1].name': _json[that.data.pickerValue[1]].areaname,
          'selectAddressData[1].id': _json[that.data.pickerValue[1]].id,
          'selectAddressData[1].index': that.data.pickerValue[1]
        });
        that._getDistrictData();
      }
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    var that = this;
    var _keyName = 'districtData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        that.setData({
          districtData: _json
        });
        that.setData({
          'selectAddressData[2].name': _json[that.data.pickerValue[2]].areaname,
          'selectAddressData[2].id': _json[that.data.pickerValue[2]].id,
          'selectAddressData[2].index': that.data.pickerValue[2]
        });
      }
    });
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      'pickerValue[0]': val[0],
      'pickerValue[1]': val[1],
      'pickerValue[2]': val[2]
    });
    this._initAddressInfo();
  },
  //城市结果
  resultAdd_v1: function () {
    let seleData = this.data.selectAddressData;
    let district = {
      itemValue1: seleData[0].id,
      itemName1: seleData[0].name,
      itemValue2: seleData[1].id,
      itemName2: seleData[1].name,
      itemValue3: seleData[2].id,
      itemName3: seleData[2].name
    };
    this._initDistrict('', district);
    this._closeDateLw_v1();
  },
  //初始化自定义表单
  _initCustomForm(data) {
    if (app._isTextEmpty(data.form)) {
      this.setData({
        isForm: false
      });
      return;
    }
    if (data.form.length == 0) {
      this.setData({
        isForm: false
      });
      return;
    }
    this.setData({
      isForm: true
    });
    this.setData({
      customDatas: data.form
    });
  },
  //其他信息值绑定
  cItemInp(e) {
    let citemidx = e.currentTarget.dataset.citemidx;
    let val = e.detail.value;
    this.setData({
      ['customDatas[' + citemidx + '].value']: val
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    var query = wx.createSelectorQuery();
    query.select('.topback').boundingClientRect(function (res) {
      that.setData({
        tabScrollTop: res.top + 10   //根据实际需求加减值
      });
    }).exec();
  },
  onPageScroll(e) {
    if (e.scrollTop >= this.data.tabScrollTop) {
      this.setData({
        showBack: true
      });
    } else if (e.scrollTop < this.data.tabScrollTop) {
      this.setData({
        showBack: false
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //获取图片验证码
  getimgdata(data) {
    let that = this;
    let urlStr = app.getNetAddresss("home-page.getCaptcha");
    if (data && data.captcha) {
      if (data.captcha) {
        that.setData({
          imgcode: data.captcha.img
        });
      }
    } else {
      app._getNetWork({
        url: urlStr,
        validateBol: 2,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.captcha) {
              that.setData({
                imgcode: res.data.captcha.img
              });
            }
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }

  },

  //判断是否需要邀请码
  _initInviteCode(data) {
    let that = this;
    // let urlStr = app.getNetAddresss("member.register.getInviteCode");

    // app._getNetWork({
    // 	url: urlStr,
    // 	validateBol:2,
    // 	success: function(resdata) {
    // 		var res = resdata.data;
    // 		if (res.result == 1) {
    // 			if (res.data.status == 1) {
    that.setData({
      invite: data.status,
      isrequired: data.required,
      country_code: data.country_code,
    });
    if (data.invitation_code) {
      that.setData({
        'form.invite_code': data.invitation_code.invite_code
      });
    }
    // 			}
    // 		}
    // 	},
    // 	fail: function(res) {
    // 		console.log(res);
    // 	}
    // });
  },
  //获取diy 状态信息
  // _getDiyFormStatus() {
  // 	let that = this;
  // 	let urlStr = app.getNetAddresss("setting.get-register-diy-form");
  // 	app._getNetWork({
  // 		url: urlStr,
  // 		validateBol:2,
  // 		success: function(resdata) {
  // 			var res = resdata.data;
  // 			if (res.result == 1) {
  // 				if (res.data.status == 1) {
  // 					that.setData({
  // 						diyStatus: 1,
  // 						form_id: res.data.form_id
  // 					})
  // 					that._getDiyFormInfo(res.data.form_id)
  // 				} else {
  // 					that.setData({
  // 						diyStatus: 0
  // 					})
  // 				}
  // 			} else {
  // 				that.setData({
  // 					diyStatus: 0
  // 				})
  // 			}
  // 		},
  // 		fail: function(res) {
  // 			console.log(res);
  // 			that.setData({
  // 				diyStatus: 0
  // 			})
  // 		}
  // 	});
  // },
  //获取diy 信息
  _getDiyFormInfo(data) {
    let that = this;
    // let urlStr = app.getNetAddresss("plugin.diyform.api.diy-form.get-diy-form-by-id");
    // urlStr += '&form_id=' + id;
    // app._getNetWork({
    // 	url: urlStr,
    // 	validateBol:2,
    // 	success: function(resdata) {
    // var res = resdata.data;
    // if (res.result == 1) {
    that.setData({
      diyform: data,
      form_id:data.id,
      'datas.form_id':data.id
    });
    let fields = that.data.diyform.fields;
    let diydata = that.data.diydata;
    let f = {};
    for (var field in fields) {
      if (that.data.types[fields[field].data_type] == 'diycheckbox') {
        f = {
          name: field,
          data: fields[field],
          value: [],
          type: that.data.types[fields[field].data_type],
        };
      } else if (that.data.types[fields[field].data_type] == 'diyselect') {
        let tp_textArr = [];
        for (let i = 0; i < fields[field].tp_text.length; i++) {
          tp_textArr.push({
            name: fields[field].tp_text[i]
          });
        }

        f = {
          name: field,
          data: fields[field],
          value: '',
          type: that.data.types[fields[field].data_type],
          diysishow: false,
          sitem: tp_textArr
        };
      } else if (that.data.types[fields[field].data_type] == 'diycity') {
        f = {
          name: field,
          data: fields[field],
          value: '',
          type: that.data.types[fields[field].data_type],
          showAdd: false
        };

      } else if (that.data.types[fields[field].data_type] == 'diydate') {
        f = {
          name: field,
          data: fields[field],
          value: '',
          type: that.data.types[fields[field].data_type],
          timeShow: false,
          currentDate: new Date().getTime()
        };
      } else if (that.data.types[fields[field].data_type] == 'diyimage') {
        f = {
          name: field,
          data: fields[field],
          imgUrls: fields[field].value ? fields[field].value : [],
          isPhoto: false,
          type: that.data.types[fields[field].data_type],
        };

      } else {
        f = {
          name: field,
          data: fields[field],
          value: '',
          type: that.data.types[fields[field].data_type],
        };
      }
      diydata.push(f);
      that.setData({
        diydata: diydata
      });
    }
    // }
    // 	},
    // 	fail: function(res) {
    // 		console.log(res);
    // 	}
    // });
  },
  onRead_1(e) {
    try {
      let diydata = this.data.diydata;
      let index = e.currentTarget.dataset.idex;
      if (diydata[index].type == "diyimage") {
        if (diydata[index].imgUrls.length >= diydata[index].data.tp_max) {
          wx.showToast({
            title: `最多只能上传${diydata[index].data.tp_max}张`,
            icon: 'none',
            duration: 1000
          });
          return;
        }
      }
      // for (var i = 0; i < diydata.length; i++){
      //   if(diydata[i].type == "diyimage"){
      //     if(diydata[i].imgUrls.length >= diydata[i].data.tp_max){
      //       wx.showToast({
      //         title: `最多只能上传${diydata[i].data.tp_max}张`,
      //         icon:'none',
      //         duration:1000
      //       })
      //       return
      //     }
      //   }
      // }
      // console.log(this.data.diydata)
    } catch (err) { console.log(err); }
    let name = e.currentTarget.dataset.name;
    this.setData({
      setname: name
    });
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        wx.compressImage({
          src: tempFilePaths[0], // 图片路径
          quality: 60, // 压缩质量
          success(e) {
            let photourl = e.tempFilePath;

            wx.uploadFile({
              url: urlStr,
              filePath: photourl,
              name: 'file',
              formData: {
                attach: that.data.setname
              },
              success(resdata) {
                var res = JSON.parse(resdata.data);
                if (res.result == 1) {
                  let diydata = that.data.diydata;
                  for (var i = 0; i < diydata.length; i++) {
                    if (diydata[i].name == res.data.attach) {
                      diydata[i].imgUrls.push(res.data.img_url);
                    }
                  }
                  that.setData({
                    diydata: diydata
                  });
                } else {
                  wx.showToast({
                    icon: 'none',
                    title: res.msg,
                    duration: 1500
                  });
                }
              }
            });
          },
          fail(e) {
            console.log(e);
          },
          complete(e) {

          }
        });
      }
    });
  },
  removeImg: function (e) {
    let delIndex = e.currentTarget.dataset.indexc;
    let index_1 = e.currentTarget.dataset.index;
    let diydata = this.data.diydata;
    diydata[index_1].imgUrls.splice(delIndex, 1);
    this.setData({
      diydata: diydata
    });
  },
  //获取是否开启协议
  _getProtocolStatus(data) {
    let that = this;
    // let urlStr = app.getNetAddresss("setting.get-member-protocol");
    // app._getNetWork({
    // 	url: urlStr,
    // 	validateBol:2,
    // 	success: function(resdata) {
    // 		var res = resdata.data;
    // 		if (res.result == 1) {
    that.setData({
      agreementStatus: data.protocol === "1" || data.protocol === 1,
      protocol_content: data.content,
      protocol_title: data.title,
      agreement_name: data.agreement_name || '平台协议',
      PlatformAgreement: data.new_agreement
    });
    // let article = that.data.protocol_content;
    /**
           * WxParse.wxParse(bindName , type, data, target,imagePadding)
           * 1.bindName绑定的数据名(必填)
           * 2.type可以为html或者md(必填)
           * 3.data为传入的具体数据(必填)
           * 4.target为Page对象,一般为this(必填)
           * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
           */
    // WxParse.wxParse('article', 'html', article, that);
    // 		} else(
    // 			that.setData({
    // 				agreementStatus: false
    // 			})
    // 		)
    // 	},
    // 	fail: function(res) {
    // 		that.setData({
    // 			agreementStatus: false
    // 		})
    // 	}
    // });
  },
  editCustom(e) {
    let key = e.detail.value;
    this.setData({
      'form.custom_value': key
    });
  },
  // 新的合并接口
  getAllData() {
    let that = this;
    let urlStr = app.getNetAddresss("member.register.bindApiData");
    try {
      var value = wx.getStorageSync('isset');
      if (value) {
        that.setData({
          isset: value
        });
      }
    } catch (e) {
      console.log(e);
    }
    if (this.data.isset) {
      wx.removeStorage({
        key: 'isset',
        success(res) {
          console.log(res.data);
        }
      });
      urlStr += '&close=' + 1;
    }
    app._postNetWork({
      url: urlStr,
      validateBol: 2,
      data: {
        not_validate_page: '0'
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            formOpen: (res.data.form_open == "1" ? true : false)
          });
          if (res.data.get_register_diy_form && res.data.get_register_diy_form.status == 1) {
            that.setData({
              diyStatus: 1,
              form_id: res.data.get_register_diy_form.form_id
            });
            if (res.data.get_diy_form_by_id) {
              that._getDiyFormInfo(res.data.get_diy_form_by_id);
            }
          } else {
            that.setData({
              diyStatus: 0
            });
          }
          if (res.data.get_member_protocol) {
            that._getProtocolStatus(res.data.get_member_protocol);
            if (res.data.get_member_protocol.form) {
              that._initCustomForm(res.data.get_member_protocol.form);
              if (res.data.get_member_protocol.form.base) {
                that.setData({
                  form_address: res.data.get_member_protocol.form.base.address == '1' ? res.data.get_member_protocol.form.base.address : '',
                  form_birthday: res.data.get_member_protocol.form.base.birthday == '1' ? res.data.get_member_protocol.form.base.birthday : false,
                  form_sex: res.data.get_member_protocol.form.base.sex == '1' ? res.data.get_member_protocol.form.base.sex : false,
                  form_name: res.data.get_member_protocol.form.base.name == '1' ? true : false,
                  is_custom: res.data.get_member_protocol.custom_field.is_custom == '1' ? true : false,
                  custom_title: res.data.get_member_protocol.custom_field.custom_title,
                  agreementCB: res.data.get_member_protocol?.default_tick == 1 ? true : false //是否默认勾选
                });
              }
            }
            if (res.data.get_member_protocol.register) {
              that.setData({
                top_img: res.data.get_member_protocol.register.top_img,
                title1: res.data.get_member_protocol.register.title1,
                title2: res.data.get_member_protocol.register.title2,
                is_password: res.data.get_member_protocol.register.is_password
              });
            }
            if (res.data.get_member_protocol.member) {
              let member = res.data.get_member_protocol.member;
              if (member.birthmonth < 10) {
                member.birthmonth = `-0${member.birthmonth}`;
              } else {
                member.birthmonth = `-${member.birthmonth}`;
              }
              if (member.birthday < 10) {
                member.birthday = `-0${member.birthday}`;
              } else {
                member.birthday = `-${member.birthday}`;
              }
              if(res.data.name_must){
                that.setData({
                  name_must:res.data.name_must == '1'?true:false
                });
              }
              that.setData({
                districtName: `${member.province_name}${member.city_name}${member.area_name}`,
                'form.address': member.address,
                'form.birthday': `${member.birthyear}${member.birthmonth}${member.birthday}`,
                sexName: member.gender == 0 ? '女' : '男',
                //  customDatas: member.member_form,
                'form.custom_value': member.custom_value
              });
            }

          }

          if (res.data.get_captcha) {
            that.getimgdata(res.data.get_captcha);
          }

          if (res.data.getInviteCode) {
            that.setData({
              default_invite: res.data.getInviteCode.default_invite
            });
            that._initInviteCode(res.data.getInviteCode);
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //绑定国家区号的值
  countryinp(e) {
    let val = e.detail.value;
    this.setData({
      "form.country": val.trim()
    });
  },
  //绑定图形验证码的值
  captchainp(e) {
    let val = e.detail.value;
    this.setData({
      "form.captcha": val.trim()
    });
  },
  //绑定手机号的值
  mobileinp(e) {
    let val = e.detail.value;
    this.setData({
      "form.mobile": val.trim()
    });
  },
  sjnz(e) {
    let val = e.detail.value;
    this.setData({
      "form.mobile": val.trim()
    });
  },
  //绑定验证码的值
  codeinp(e) {
    let val = e.detail.value;
    this.setData({
      "form.code": val.trim()
    });
  },
  //绑定邀请码的值
  inviteinp(e) {
    let val = e.detail.value;
    this.setData({
      "form.invite_code": val.trim()
    });
  },
  //绑定设置密码的值
  passwordinp(e) {
    let val = e.detail.value;
    this.setData({
      "form.password": val.trim()
    });
  },
  //绑定确认密码的值
  conpasswordinp(e) {
    let val = e.detail.value;
    this.setData({
      "form.confirm_password": val.trim()
    });
  },
  //绑定注册协议的值
  agreementCBinp(e) {
    let bol = e.detail;
    this.setData({
      agreementCB: bol
    });
  },
  //打开注册协议
  goAgreement() {
    this.setData({
      show2: true
    });
  },
  popClose() {
    this.setData({
      show2: false
    });
  },
  openPlatformAgreement() {
    this.setData({
      showPlatformAgreement: true
    });
  },
  closePlatformAgreement() {
    this.setData({
      showPlatformAgreement: false
    });
  },
  sendCode(e) {
    if (this.data.start1) {
      return false;
    }
    let time = 60;
    let that = this;
    that.setData({
      "start1": true,
      "codetext": "(" + time + ")秒后重新获取"
    });
    let set = setInterval(function () {
      that.setData({
        codetext: "(" + --time + ")秒后重新获取",
      });
    }, 1000);
    setTimeout(function () {
      that.setData({
        codetext: "获取短信验证码",
        start1: false
      });
      clearInterval(set);
    }, 60000);
    that.verificationCode(set);
  },
  //发送验证码
  verificationCode(set) {
    let that = this;
    if (app._isTextEmpty(this.data.form.country)) {
      wx.showToast({
        icon: 'none',
        title: '请输入国际区号',
        duration: 1500
      });
      that.setData({
        codetext: "获取短信验证码",
        start1: false
      });
      clearInterval(set);
      return;
    }
    if (app._isTextEmpty(this.data.form.mobile)) {
      wx.showToast({
        icon: 'none',
        title: '请填写手机号',
        duration: 1500
      });
      that.setData({
        codetext: "获取短信验证码",
        start1: false
      });
      clearInterval(set);
      return;
    }

    if (this.data.form.country == "86" && app._isMoblie(this.data.form.mobile)) {
      wx.showToast({
        icon: 'none',
        title: '请填写正确的手机号',
        duration: 1500
      });
      return;
    }

    if (app._isTextEmpty(this.data.form.captcha) && this.data.imgcode) {
      wx.showToast({
        icon: 'none',
        title: '请填图形验证码',
        duration: 1500
      });
      that.setData({
        codetext: "获取短信验证码",
        start1: false
      });
      clearInterval(set);
      return;
    } else {
      let urlStr = app.getNetAddresss("member.register.sendCodeV2");
      urlStr += '&mobile=' + this.data.form.mobile;
      urlStr += '&state=' + this.data.form.country;
      urlStr += '&captcha=' + this.data.form.captcha;
      urlStr += '&code=' + this.data.form.code;
      // 发送获取验证码的请求
      app._getNetWork({
        url: urlStr,
        validateBol: 2,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            wx.showToast({
              icon: 'none',
              title: '已发送',
              duration: 1500
            });
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            //刷新图形验证码
            that.setData({
              'form.captcha': '',
              start1: false,
              codetext: "获取短信验证码",
            });
            clearTimeout(set);
            that.getimgdata();
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  //自定义表单值绑定
  tpnameinp(e) {
    let val = e.detail.value;
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].value"]: val
    });
  },
  diytextareainp(e) {
    let val = e.detail.value;
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].value"]: val
    });
  },
  checkboxinp(e) {
    let val = e.detail;
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].value"]: val
    });
  },
  diyselectBtn(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].diysishow"]: true
    });
  },
  sitemClose(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].diysishow"]: false
    });
  },
  sitemSelectBtn(e) {
    let idx = e.target.dataset.idex;
    let val = e.detail.name;
    this.setData({
      ["diydata[" + idx + "].value"]: val,
      ["diydata[" + idx + "].diysishow"]: false
    });
  },
  raidinp(e) {
    let val = e.detail;
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].value"]: val
    });
  },
  //所在地选择显示
  showAddBtn(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].showAdd"]: true
    });
  },
  // 关闭选择收货地址
  _closeDateLw: function (e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].showAdd"]: false
    });
  },

  //城市结果
  resultAdd: function (e) {
    let idx = e.currentTarget.dataset.idex;
    let seleData = this.data.selectAddressData;
    let retCity = seleData[0].name + ' ' + seleData[1].name + ' ' + seleData[2].name;
    this.setData({
      ["diydata[" + idx + "].value"]: retCity,
      ["diydata[" + idx + "].showAdd"]: false
    });
  },
  //自定义日期选择
  openPicker(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].timeShow"]: true
    });
  },
  PickerClose(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].timeShow"]: false
    });
  },
  PickerChange(event) {
    let idx = event.currentTarget.dataset.idex;
    let time = event.detail;
    this.setData({
      ["diydata[" + idx + "].currentDate"]: time
    });
  },
  birthdayconfirm(e) {
    let idx = e.currentTarget.dataset.idex;
    let time = e.detail;
    let changtime = this.timestampToTime(time);
    this.setData({
      ["diydata[" + idx + "].value"]: changtime,
      ["diydata[" + idx + "].timeShow"]: false
    });
  },
  timestampToTime(timestamp) {
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate());
    return Y + M + D;
  },
  //注册
  register() {
    let is_customDatas = {},
      adress = {};
    is_customDatas.customDatas = this.data.customDatas;
    adress.province_name = this.data.form.province_name;
    adress.city_name = this.data.form.city_name;
    adress.area_name = this.data.form.area_name;
    adress.province = this.data.form.province;
    adress.city = this.data.form.city;
    adress.area = this.data.form.area;
    adress.address = this.data.form.address;
    let is_form = {
      invite_code: this.data.form.invite_code,
      country: this.data.form.country,
      mobile: this.data.form.mobile,
      mobileErr: this.data.form.mobileErr,
      password: this.data.form.password,
      passwordErr: this.data.form.passwordErr,
      confirm_password: this.data.form.confirm_password,
      confirm_passwordErr: this.data.form.confirm_passwordErr,
      captcha: this.data.form.captcha,
      gender: this.data.form.gender,
      code: this.data.form.code,
      birthday: this.data.form.birthday,
      custom_value: this.data.form.custom_value,
      close: this.data.form.close
    };
    is_form.address = adress;
    is_form.realname = this.data.form.realname;
    is_form.customDatas = is_customDatas.customDatas;
    let that = this;


    if (this.data.formOpen && (this.data.customDatas instanceof Array) && this.data.editType != 1) {
      let result = this.data.customDatas.every((item) => {return (item.value != "");});
      if (!result) {
        wx.showToast({
          icon: 'none',
          title: '请先填写自定义信息',
          duration: 1500
        });
        return;
      }
    }

    //防止快速点击，重复触发
    if (this.data.repeatStatus) {
      return;
    }
    this.setData({
      repeatStatus: true
    });

    //判断是否从设置页面跳转
    if (!this.data.isset) {
      const {
        ...formData
      } = is_form;
      this.setData({
        is_form: formData
      });
    }
    if (this.data.isset) {
      wx.removeStorage({
        key: 'isset',
        success(res) {
          console.log(res.data);
        }
      });
      const {
        ...formData
      } = is_form;
      this.setData({
        is_form: formData
      });
      that.data.is_form.close = 1;
    }
    let urlStr = app.getNetAddresss("member.member.bindMobile");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: that.data.is_form,
      validateBol: 2,
      success: function (resdata) {
        that.setData({
          repeatStatus: false
        });
        var res = resdata.data;
        if (res.result == 1) {
          app.resetBasicInfo();
          if(that.data.changidInfo && that.data.changidInfo.change_uid){
            // 更新uid为合并后的会员id
            wx.setStorage({
              key: "yz_uid",
              data: that.data.changidInfo.change_uid,
            });
          }
          
          if (that.data.diyStatus == 0) {
            wx.showToast({
              icon: 'none',
              title: '绑定成功',
              duration: 1500
            });
            if (that.data.anchorApplyBol) {
              wx.navigateBack({
                delta: 1
              });
              return;
            }
            if (that.data.isset == 1 && !that.data.editType) {
              wx.removeStorage({
                key: 'isset',
                success(res) {}
              });
              wx.reLaunch({
                url: '/' + app.globalData.beforeBindMobilePage,
                fail: (res) => {
                  wx.reLaunch({
                    url: '/packageG/index/index'
                  });
                }
              });
              return
            } else {
              that.gotourl();
            }

          } else if (that.data.diyStatus == 1) {
            //去提交diy
            let child = that.selectComponent('.dsfrom');
            child.submit();
            // that.postDiy();
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }

      },
      fail: function (res) { }
    });
  },
  //先验证是否导致会员id变更
  getPrepBind() {
    let that = this;
    if(this.data.name_must && this.data.editType!='1'){
      if (app._isTextEmpty(this.data.form.realname)) {
        app.tips('请输入姓名');
        return;
      }
    }
    if (app._isTextEmpty(this.data.form.country)) {
      wx.showToast({
        icon: 'none',
        title: '请输入国际区号',
        duration: 1500
      });
      return;
    }

    if (app._isTextEmpty(this.data.form.mobile)) {
      wx.showToast({
        icon: 'none',
        title: '请填写手机号',
        duration: 1500
      });
      return;
    }

    if (this.data.form.country == "86" && app._isMoblie(this.data.form.mobile)) {
      wx.showToast({
        icon: 'none',
        title: '请填写正确的手机号',
        duration: 1500
      });
      return;
    }

    if (app._isTextEmpty(this.data.form.code)) {
      wx.showToast({
        icon: 'none',
        title: '请填验证码',
        duration: 1500
      });
      return;
    }

    if (this.data.is_password == '1') {
      if (app._isTextEmpty(this.data.form.password)) {
        wx.showToast({
          icon: 'none',
          title: '请填写密码',
          duration: 1500
        });
        return;
      }
      if (app._isTextEmpty(this.data.form.confirm_password)) {
        wx.showToast({
          icon: 'none',
          title: '请填写确认密码',
          duration: 1500
        });
        return;
      }
      if (this.data.form.password != this.data.form.confirm_password) {
        wx.showToast({
          icon: 'none',
          title: '两次密码不一致',
          duration: 1500
        });
        return;
      }
    }
    if (this.data.isrequired == 1) {
      if (app._isTextEmpty(this.data.form.invite_code)) {
        wx.showToast({
          icon: 'none',
          title: '请填写邀请码',
          duration: 1500
        });
        return;
      }
    }
    if(this.data.formOpen && this.data.isForm && this.data.editType != 1){
      for(let i = 0;i<this.data.customDatas.length;i++){
        if(app._isTextEmpty(this.data.customDatas[i].value)){
          app.tips(`请输入${this.data.customDatas[i].name}`);
          return;
        }
      }
    }
    if (this.data.imgcode) {
      if (app._isTextEmpty(this.data.form.captcha)) {
        wx.showToast({
          icon: 'none',
          title: '图形验证码不能为空',
          duration: 1500
        });
        return;
      }
    }
    // 位置调整
    if (this.data.diyStatus == 1) {
      this.validation();
      if (!this.data.isValidation) {
        return;
      }
    }

    if(this.data.PlatformAgreement){
      if(!this.data.agreementCB){
        wx.showToast({
          icon: 'none',
          title: "请先勾选同意"+this.data.agreement_name,
          duration: 2000
        });
        return;
      }
    }

    if (this.data.agreementStatus) {
      if (!this.data.agreementCB) {
        wx.showToast({
          icon: 'none',
          title: "请先勾选同意"+ this.data.protocol_title || '会员注册协议',
          duration: 2000
        });
        return;
      }
    }
    //防止快速点击，重复触发
    if (this.data.repeatStatus) {
      return;
    }
    this.setData({
      repeatStatus: true
    });

    //判断是否从设置页面跳转
    if (!this.data.isset) {
      const {
        ...formData
      } = this.data.form;
      this.setData({
        form: formData
      });
    }
    Object.assign(this.data.form, this.data.orderLocationObj);
    let urlStr = app.getNetAddresss("member.member.prepBind");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: this.data.form,
      validateBol: 2,
      success: function (resdata) {
        that.setData({
          repeatStatus: false
        });
        var res = resdata.data;
        if (res.result == 1) {
          if (res.data.is_show) {
            // 显示 导致会员id变更 弹窗
            let basic_info = wx.getStorageSync('yz_basic_info');
            that.setData({
              balance:basic_info.balance,
              point:basic_info.point,
              showChangeID: true,
              changidInfo: {
                uid: res.data.uid,
                change_uid: res.data.change_uid
              }
            });
          } else {
            //不显示提示弹窗
            that.register();
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }

      },
      fail: function (res) { }
    });
  },
  closeChangeId() {
    this.setData({
      showChangeID: false
    });
  },
  //验证参数
  validation() {
    this.setData({
      isValidation: true
    });
    this.data.diydata.forEach(item => {
      if (item.data.tp_must == 1 && !item.value && item.type) {
        wx.showToast({
          icon: 'none',
          title: item.data.tp_name + '必须填写哦',
          duration: 1500
        });
        this.setData({
          isValidation: true
        });
      }
      if (item.type == 'diycheckbox' && item.value.length == 0) {
        wx.showToast({
          icon: 'none',
          title: item.data.tp_name + '必须选择哦',
          duration: 1500
        });
        this.setData({
          isValidation: false
        });
      }
    });
  },
  postDiy(e) {
    let that = this;
    let formData = e.detail;
    // let formObject = {};
    // this.data.diydata.forEach(item => {
    //   if (item.type == 'diyimage') {
    //     formObject[item.name] = item.imgUrls;
    //   } else {
    //     formObject[item.name] = item.value;
    //   }
    // });
    // formData.push(formObject);

    let json = {
      form_data: formData,
      form_id: this.data.form_id,
      "form_type": "register"
    };
    let urlStr = app.getNetAddresss("plugin.diyform.api.diy-form.save-diy-form-data");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {

          wx.showToast({
            title: '绑定成功',
            icon: 'none',
            duration: 1500,
            success: function () {
              setTimeout(function () {
                that.gotourl();
                //要延时执行的代码
              }, 1500); //延迟时间
            },
          });
          if(this.data.is_code){
            this.address_codeMethod();
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }

      },
      fail: function (res) { }
    });
  },
  address_codeMethod(basic_infoData = wx.getStorageSync('yz_basic_info')){
    if(app.data.address_code){
      try {
        let basic_info = basic_infoData;
        if(basic_info.plugin_setting.address_code && basic_info.plugin_setting.address_code.enable){
          let urlStr = app.getNetAddresss('plugin.address-code.frontend.index.set-address');
          app._postNetWork({
            url: urlStr,
            data: {
              address_id: app.data.address_code,
            },
            success: (resdata) => {
              var res = resdata.data;
              if (res.result == 1) {
                app.data.address_code = '';
              }
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    }
  },
  gotourl() {
    let that = this;
    if (that.data.fromApp != 0 && that.data.fromApp != undefined) {
      if (that.data.fromApp == 1||that.data.fromApp == 3) {
        //fromApp == 3 从邀请码进入
        wx.reLaunch({
          url: '/' + app.globalData.beforeBindMobilePage,
          fail: () => {
            wx.reLaunch({
              url: '/packageG/index/index'
            });
          }
        });
      } else if (that.data.fromApp == 2) {
        // 会员修改手机进入
        wx.reLaunch({
          url: '/packageG/member_v2/member_v2'
        });
      } else if (that.data.fromApp == 4) {
        wx.reLaunch({
          url: '/packageG/pages/member/extension/extension'
        });
      } else if (that.data.fromApp == 5) {
        wx.reLaunch({
          url: '/' + app.globalData.beforeBindMobilePage,
          fail: () => {
            wx.reLaunch({
              url: '/packageG/index/index'
            });
          }
        });
      }

    } else if (!that.data.yzredirect) {
      wx.navigateBack({
        delta: 1,
        fail:()=> {
          wx.reLaunch({
            url: '/packageG/index/index'
          });
        }
      });
    } else {
      try {
        wx.reLaunch({
          url: '/' + that.data.yzredirect,
          fail:()=> {
            wx.reLaunch({
              url: '/packageG/index/index'
            });
          }
        });
      } catch (e) {
        wx.navigateBack({
          delta: 1,
          fail:()=> {
            wx.reLaunch({
              url: '/packageG/index/index'
            });
          }
        });
      }
    }
  },
  bindDateChange: function (e) {
    let idx = e.target.dataset.idex;
    let time = e.detail.value;
    this.setData({
      ["diydata[" + idx + "].value"]: time,
      ["diydata[" + idx + "].timeShow"]: false,
      date: time
    });
  },
  //获取经纬度
  getCurrentOrderLocation() {
    this._getLocation((mapdata, e) => {
      let orderLocationObj = {
        positioning_success: 1,
        register_province: mapdata.address_component.province,
        register_city: this.data.city
      };
      this.data.orderLocationObj = orderLocationObj;
    });
  },

  async checkAlbum(scopeName) {
    let writePhotosAlbum = await this.getAuthSetting(scopeName);
    return new Promise( (resolve, reject) => {
      if (!writePhotosAlbum) {
        wx.showModal({
          title: '请开启授权',
          content: '是否跳转设置页开启授权',
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting[scopeName]) {
                    resolve(true);
                  } else {
                    resolve(false);
                  }
                }
              });
            } else if (res.cancel) {
              resolve(false);
            }
          },
          fail: () => {
            resolve(false);
          }
        });
      } else resolve(true);

    });

  },
  getAuthSetting(authName) {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success(res) {
          if (!res.authSetting[authName]) {
            wx.authorize({
              scope: authName,
              success() {
                resolve(true);
              },
              fail() {
                resolve(false);
              }
            });
          } else resolve(true);
        },
        fail() {
          resolve(false);
        }
      });
    });
  },
  tips(msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    });
    return false;
  },
  realnameInp(e){
    let key = e.detail.value;
    this.setData({
      'form.realname':key
    });
  },
  SetPwdClick () {
    this.setData({
      visibleSet: !this.data.visibleSet
    });
  },
  surePwdClick () {
    this.setData({
      visibleSure: !this.data.visibleSure
    });
  },
});
